<template>

  <div class="homeDetail">

    <div class="tabr-nav-title">
       <van-nav-bar
        :title="status === 'feedback' ? '处置反馈' : '提交办结'"
        style="width: 100%; height: 44px"
        left-arrow
        @click-left="onClickLeft"
      />
    </div>

    <div class="formList">
       <van-form
        > <van-cell-group inset
          > <van-field
            v-model="state.fromData.accumulatedWaterStartTime"
            is-link
            readonly
            name="accumulatedWaterStartTime"
            label="积水开始时间"
            placeholder="请选择"
            @click="showPicker1 = true"
          /> <van-popup
            v-model:show="showPicker1"
            destroy-on-close
            position="bottom"
            > <van-picker-group
              title="积水开始时间"
              :tabs="['选择日期', '选择时间']"
              @confirm="onConfirm(1)"
              @cancel="showPicker1 = false"
              > <van-date-picker
                v-model="state.currentDate1"
                :min-date="minDate"
                :max-date="maxDate"
              /> <van-time-picker v-model="state.currentTime1" />
              </van-picker-group
            > </van-popup
          > <van-field
            v-model="state.fromData.accumulatedWaterEndTime"
            is-link
            readonly
            name="accumulatedWaterEndTime"
            label="积水结束时间"
            placeholder="请选择"
            @click="showPicker2 = true"
          /> <van-popup
            v-model:show="showPicker2"
            destroy-on-close
            position="bottom"
            > <van-picker-group
              title="积水结束时间"
              :tabs="['选择日期', '选择时间']"
              @confirm="onConfirm(2)"
              @cancel="showPicker2 = false"
              > <van-date-picker
                v-model="state.currentDate2"
                :min-date="minDate"
                :max-date="maxDate"
              /> <van-time-picker v-model="state.currentTime2" />
              </van-picker-group
            > </van-popup
          > <van-field
            v-model="state.fromData.cessationRainTime"
            is-link
            readonly
            name="cessationRainTime"
            label="停雨时间"
            placeholder="请选择"
            @click="showPicker3 = true"
          /> <van-popup
            v-model:show="showPicker3"
            destroy-on-close
            position="bottom"
            > <van-picker-group
              title="停雨时间"
              :tabs="['选择日期', '选择时间']"
              @confirm="onConfirm(3)"
              @cancel="showPicker3 = false"
              > <van-date-picker
                v-model="state.currentDate3"
                :min-date="minDate"
                :max-date="maxDate"
              /> <van-time-picker v-model="state.currentTime3" />
              </van-picker-group
            > </van-popup
          > <van-field
            v-model="state.fromData.accumulatedWaterDepth"
            name="accumulatedWaterDepth"
            label="积水深度"
            placeholder="请输入"
            > <template #button> <span>cm</span> </template> </van-field
          > <van-field
            v-model="state.fromData.accumulatedWaterArea"
            name="accumulatedWaterArea"
            label="积水面积"
            placeholder="请输入"
            > <template #button> <span>m²</span> </template> </van-field
          > <van-field
            v-model="state.fromData.accumulatedWaterTime"
            name="accumulatedWaterTime"
            label="积水时长"
            placeholder="请输入"
            > <template #button> <span>h</span> </template> </van-field
          > <van-field
            v-model="state.fromData.retreatWaterTime"
            name="retreatWaterTime"
            label="退水时长"
            placeholder="请输入"
            > <template #button> <span>h</span> </template> </van-field
          > <van-field
            v-model="state.fromData.ifDisconnection"
            is-link
            readonly
            name="ifDisconnection"
            label="是否断交"
            placeholder="点击选择是否断交"
            @click="showPicker4 = true"
          /> <van-popup
            v-model:show="showPicker4"
            destroy-on-close
            position="bottom"
            > <van-picker
              :columns="columns"
              :model-value="[state.fromData.ifDisconnection]"
              @confirm="confirm1"
              @cancel="showPicker4 = false"
            /> </van-popup
          > <van-field
            v-if="state.fromData.ifDisconnection == '是'"
            v-model="state.fromData.disconnectionContent"
            name="disconnectionContent"
            label="断交时长"
            placeholder="请输入"
            > <template #button> <span>h</span> </template> </van-field
          > <van-field
            v-model="state.fromData.ifTrouble"
            is-link
            readonly
            name="ifTrouble"
            label="是否受困"
            placeholder="点击选择是否受困"
            @click="showPicker5 = true"
          /> <van-popup
            v-model:show="showPicker5"
            destroy-on-close
            position="bottom"
            > <van-picker
              :columns="columns"
              :model-value="[state.fromData.ifTrouble]"
              @confirm="confirm2"
              @cancel="showPicker5 = false"
            /> </van-popup
          > <van-field
            v-if="state.fromData.ifTrouble == '是'"
            v-model="state.fromData.predicamentReasons"
            name="predicamentReasons"
            label="受困情况"
            placeholder="请输入"
          /> <van-field
            v-model="state.fromData.bz"
            name="bz"
            label="备注"
            placeholder="请输入"
          />
          <div class="newList">

            <div class="list" v-for="(item, index) in state.list" :key="index">

              <div class="top"> {{ item[0] }} </div>

              <div class="bottom">
                 <van-switch
                  active-color="#00b01b"
                  style="width: 100%"
                  v-model="item[1]"
                />
                <div class="tips">
                   <span
                    :style="{
                      color: item[1] == 1 ? '#fff' : '#000',
                    }"
                    >{{ item[1] == 1 ? '已完成' : '未完成' }}</span
                  > <span
                    class="tip"
                    :style="{
                      color: item[1] == 1 ? '#D5D5D5' : '#AAAAAA',
                    }"
                    >{{ '点击确认完成情况' }}</span
                  >
                </div>

              </div>

            </div>

          </div>

          <div class="uploadButton" v-if="status === 'submit'">
             <van-uploader
              v-model="fileList"
              :before-read="beforeRead"
              :after-read="afterRead"
              > <van-button type="primary" size="small"
                >上传拍摄处置后照片</van-button
              > </van-uploader
            >
          </div>
           </van-cell-group
        > </van-form
      >
    </div>

    <div class="detailFoot">
       <van-button
        style="flex: 1"
        type="primary"
        size="small"
        @click="submitClick"
        >{{ status === 'feedback' ? '确认反馈' : '确认办结' }}</van-button
      >
    </div>

  </div>

</template>

<script setup lang="ts">
  import { ref, reactive, onMounted } from 'vue'
  import { useRouter, useRoute } from 'vue-router'
  import { showFailToast, showSuccessToast } from 'vant'
  import { completion, feedback, upload } from '@/api/index.js'
  const router = useRouter()
  const route = useRoute()
  const showPicker1 = ref(false)
  const showPicker2 = ref(false)
  const showPicker3 = ref(false)
  const showPicker4 = ref(false)
  const showPicker5 = ref(false)
  const fileList = ref([])
  const ifDisconnection = ref('')
  const minDate = new Date(2020, 1, 1)
  const maxDate = new Date(2030, 12, 31)
  const columns = [
    { text: '是', value: '是' },
    { text: '否', value: '否' },
  ]
  const status = route.query.status || ''
  const state = reactive({
    fromData: {},
    currentDate1: ['2025', '05', '01'],
    currentTime1: ['12', '00'],
    currentDate2: ['2025', '05', '01'],
    currentTime2: ['12', '00'],
    currentDate3: ['2025', '05', '01'],
    currentTime3: ['12', '00'],
    list: [],
  })
  const onConfirm = (type) => {
    if (type == 1) {
      state.fromData.accumulatedWaterStartTime =
        state.currentDate1.join('-') + ' ' + state.currentTime1.join(':')
      showPicker1.value = false
    }
    if (type == 2) {
      state.fromData.accumulatedWaterEndTime =
        state.currentDate2.join('-') + ' ' + state.currentTime2.join(':')
      showPicker2.value = false
    }
    if (type == 3) {
      state.fromData.cessationRainTime =
        state.currentDate3.join('-') + ' ' + state.currentTime3.join(':')
      showPicker3.value = false
    }
  }
  const confirm1 = ({ selectedOptions }) => {
    state.fromData.ifDisconnection = selectedOptions[0]?.value
    if (selectedOptions[0]?.value == '否') {
      state.fromData.disconnectionContent = ''
    }
    showPicker4.value = false
  }
  const confirm2 = ({ selectedOptions }) => {
    state.fromData.ifTrouble = selectedOptions[0]?.value
    if (selectedOptions[0]?.value == '否') {
      state.fromData.predicamentReasons = ''
    }
    showPicker5.value = false
  }
  // 返回布尔值
  const beforeRead = (file) => {
    if (file.type !== 'image/jpeg' && file.type !== 'image/png') {
      showToast('请上传 jpg/png 格式图片')
      return false
    }
    if (fileList.value.length >= 1) {
      fileList.value.shift()
    }
    return true
  }

  // 上传
  const afterRead = (file) => {
    const formData = new FormData()
    formData.append('file', file.file)
    file.status = 'uploading'
    file.message = '上传中...'
    upload(formData).then((res) => {
      if (res.data.code === 200 && res.data.data) {
        state.fromData.fileId = res.data.data.id
        file.status = 'done'
      }
    })
  }
  const submitClick = async () => {
    let disposalMatter = state.list.map((item) => {
      return item[1] === true ? [item[0], 1] : [item[0], 0]
    })
    let isFinished = true
    if (route.query.eventType !== '快处上报' || state.fromData.riskPointId) {
      isFinished = disposalMatter.every((item) => item[1] === 1)
    }

    // console.log('打印fromData', state.fromData)
    if (
      status === 'submit' &&
      route.query.eventType == '快处上报' &&
      !state.fromData.riskPointId
    ) {
      disposalMatter = disposalMatter.filter((item) => item[1] === 1)
    }
    const obj = disposalMatter.reduce((acc, [key, value]) => {
      acc[key] = value
      return acc
    }, {})
    let params = {
      ...state.fromData,
      disposalMatter: obj,
      id: route.query.id,
      accumulatedWaterStartTime:
        state.fromData.accumulatedWaterStartTime + ':00',
      accumulatedWaterEndTime: state.fromData.accumulatedWaterEndTime + ':00',
      cessationRainTime: state.fromData.cessationRainTime + ':00',
      ifDisconnection: state.fromData.ifDisconnection == '是' ? 1 : 0,
      ifTrouble: state.fromData.ifTrouble == '是' ? 1 : 0,
    }

    if (status === 'feedback') {
      await feedback(params)
        .then((res) => {
          if (res.data.code == 200) {
            showSuccessToast('反馈成功')
            history.back()
          } else {
            showToast(res.data.message)
          }
        })
        .catch((err) => {})
    }
    if (status === 'submit') {
      if (isFinished) {
        if (state.fromData.fileId) {
          await completion(params)
            .then((res) => {
              if (res.data.code == 200) {
                showSuccessToast('提交成功')
                history.back()
              } else {
                showToast(res.data.message)
              }
            })
            .catch((err) => {})
        } else {
          showFailToast('请上传照片')
        }
      } else {
        showFailToast('请完成反馈事项')
      }
    }
  }
  const onClickLeft = () => history.back()
  onMounted(() => {
    let detailData = JSON.parse(route.query.detailData)
    for (let key in detailData.disposalMatter) {
      if (detailData.disposalMatter.hasOwnProperty(key)) {
        // 检查属性是否为对象自身的属性
        detailData.disposalMatter[key] =
          detailData.disposalMatter[key] == 1 ? true : false
      }
    }
    state.list = Object.entries(detailData.disposalMatter)
    state.detailData?.completionTime
      ? new Date(state.detailData?.completionTime).toLocaleString()
      : '-'
    state.fromData = {
      ...detailData,
      accumulatedWaterStartTime: detailData.accumulatedWaterStartTime
        ? new Date(detailData.accumulatedWaterStartTime)
            .toLocaleString()
            .replace(/\//g, '-')
        : '',
      accumulatedWaterEndTime: detailData.accumulatedWaterEndTime
        ? new Date(detailData.accumulatedWaterEndTime)
            .toLocaleString()
            .replace(/\//g, '-')
        : '',
      cessationRainTime: detailData.cessationRainTime
        ? new Date(detailData.cessationRainTime)
            .toLocaleString()
            .replace(/\//g, '-')
        : '',
      ifDisconnection: detailData.ifDisconnection == 1 ? '是' : '否',
      ifTrouble: detailData.ifTrouble == 1 ? '是' : '否',
    }
  })
</script>

<style scoped lang="less">
  .homeDetail {
  height: 100vh;
  background: #f7f8f7;
}

.homeHeader {
  padding: 10px;
  background: #fff;
  margin: 10px 0;
  display: flex;
  justify-content: space-between;
}

.tabr-nav-title {
  display: flex;
  align-items: center;
  font-weight: 600;
  height: 44px;
  font-size: 18px;
  color: #29292c;
  text-align: center;
  font-style: normal;
  background: #fff;
  width: 100vw;
}
.formList {
  height: calc(100vh - 135px);
  margin: 10px 0;
  overflow-y: auto;
  background: #fff;
  .uploadButton {
    padding: 10px;
    box-sizing: border-box;
    :deep(.van-uploader) {
      width: 100%;
      .van-uploader__input-wrapper {
        width: 100%;
        .van-button {
          width: 100%;
        }
      }
    }
  }
  .newList {
    background: #fff;
    border-radius: 10px;
    padding-bottom: 1px;
    margin-bottom: 10px;
    padding: 10px;

    .list {
      width: 100%;
      background-color: rgba(242, 242, 242, 1);
      margin-bottom: 5px;
      padding: 8px 10px;
      box-sizing: border-box;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      &:last-child {
        margin-bottom: 0;
      }
      .top {
        color: #333;
        width: calc(100% - 50px);
      }
      .bottom {
        margin-top: 5px;
        --van-switch-width: calc(100vw - 72px);
        position: relative;
        .tips {
          position: absolute;
          bottom: 10px;
          left: 40px;
          .tip {
            margin-left: 50px;
            font-size: 10px;
          }
        }
      }
    }
  }
}
.detailFoot {
  width: 100vw;
  padding: 20px;
  background: #fff;
  position: fixed;
  bottom: 0px;
  display: flex;
  justify-content: space-between;
  box-sizing: border-box;
}
</style>

